import datetime
import time

from django.db import transaction
from django.http import JsonResponse
from django.shortcuts import render
import json
from orders.models import Goods, Order, OrderDetail

# Create your views here.
def order(request):

    # 1,获取数据
    # {"1": 10, "2": 10}
    data = json.loads(request.body)

    # 处理数据
    # 订单号: 时间日期格式串  '20201113154950' + 用户id
    order_code = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(request.user.id)


    # 开启事务
    with transaction.atomic():

        # 设置保存点
        save_id = transaction.savepoint()

        # 1,生成总订单
        orders = Order.objects.create(
            uid=request.user.id,
            order_code=order_code,
            total_count=sum(data.values()),
            total_amount=0
        )


        total_amount = 0
        # 2,循环json串,生成子订单
        for gid, count in data.items():


            while True:
                # 通过gid获取商品数据
                good = Goods.objects.get(id=gid)

                # 采用悲观锁, 必须在事务里面使用
                # select * from goods where id = gid for update
                # good = Goods.objects.select_for_update().get(id=gid)

                # 注意:在生成子订单之前要判断库存够不够

                if good.stock < count:

                    # 回滚事务
                    transaction.savepoint_rollback(save_id)

                    # 如果库存不够,就报错
                    return JsonResponse({'code':1007, 'data': '商品库存足'})


                time.sleep(3)

                # 如果库存够,减库存,加销量
                # good.stock -= count
                # good.sales += count
                # good.save()

                print(request.user.id, gid, good.stock)

                # 采用乐观锁的形式，更新数据之前， 判断当前库存是否是之前查询的库存
                res = Goods.objects.filter(id=gid, stock=good.stock).update(
                    stock=good.stock-count,
                    sales=good.sales+count
                )

                if not res:
                    continue
                    # transaction.savepoint_rollback(save_id)
                    # return JsonResponse({'code':1008, 'data': '当前网络忙，请稍后再试'})



                # 生成子订单
                OrderDetail.objects.create(
                    uid=request.user.id,
                    order_code=order_code,
                    goods_id=gid,
                    counts=count,
                    price=good.price
                )

                # 循环中 不断累加每个商品的价格,获得总价
                total_amount += good.price * count

                break


        orders.total_amount = total_amount
        orders.save()

        transaction.savepoint_commit(save_id)


    return JsonResponse({'code':0, 'data': '下单成功'})